package com.fangrui.filter;

import com.alibaba.fastjson.JSONObject;
import com.fangrui.pojo.Result;
import com.fangrui.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;

//Created by ✎﹏ℳ๓独赏☆独醉 on 2025/4/27 15:03
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        获取请求url
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String url = request.getRequestURL().toString();
//        判断请求中是否包含login
        if(url.contains("/login")){
            log.info("登陆操作，直接放行");
            filterChain.doFilter(request, response);
            return;
        }
//        获取请求头中令牌
        String jwt = request.getHeader("token");
//        判断令牌是否存在
        if(!StringUtils.hasLength(jwt)){//!StringUtils.hasLength(jwt)判断字符串长度
            log.info("令牌不存在，请登录");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }
//        解析令牌，检验有效性
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            log.info("令牌失效");
            Result error = Result.error("NOT_LOGIN");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return;
        }
//        放行
        log.info("令牌合法，确认放行");
        filterChain.doFilter(request, response);
    }
}
